package com.dlc.yunguang.activity;

import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;
import butterknife.BindView;
import com.dlc.commonlibrary.adapter.CommonPagerAdapter;
import com.dlc.commonlibrary.ble.BleHelper;
import com.dlc.commonlibrary.ble.RRUA100API;
import com.dlc.commonlibrary.utils.LogPlus;
import com.dlc.commonlibrary.widget.NoScrollViewPager;
import com.dlc.commonlibrary.widget.alphatabs.AlphaTabView;
import com.dlc.commonlibrary.widget.alphatabs.AlphaTabsIndicator;
import com.dlc.yunguang.base.BaseActivity;
import com.dlc.yunguang.base.Constants;
import com.dlc.yunguang.fragment.FragmentScannerListFragment;
import com.dlc.yunguang.fragment.HomeStorekeeperFragment;
import com.dlc.yunguang.fragment.MineFragment;
import com.dlc.yunguang.helper.PreHelper;
import com.dlc.yunguang.helper.UserHelper;
import com.dlc.yunguang.R;
import com.seuic.uhf.UHFService;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import java.util.ArrayList;

public class MainActivity extends BaseActivity {

    @BindView(R.id.view_pager) NoScrollViewPager mViewPager;
    @BindView(R.id.tab_a) AlphaTabView mTabA;
    @BindView(R.id.tab_b) AlphaTabView mTabB;
    @BindView(R.id.tab_c) AlphaTabView mTabC;
    @BindView(R.id.alphaIndicator) AlphaTabsIndicator mAlphaIndicator;

    public SharedPreferences mPref;
    public final String KEY_LAST_ADDR_STRING = "key_last_addr_string";
    private BluetoothAdapter mBTadapter;
    public static RRUA100API mA100 = null;
    private boolean BT_enable_onStart = false;
    public String mLast_addr;
    private FragmentScannerListFragment bluetoothFragment;
    private UHFService mDevice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initFragments();
        try {
            mDevice = UHFService.getInstance();
        }catch (Exception e){}

    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_main;
    }

    private void initFragments() {

        Fragment homeFragment;
        homeFragment = new HomeStorekeeperFragment();

        bluetoothFragment = new FragmentScannerListFragment();
        Fragment mineFragment = new MineFragment();

        ArrayList<Fragment> fragments = new ArrayList<>();
        fragments.add(homeFragment);
        fragments.add(bluetoothFragment);
        fragments.add(mineFragment);
        mBTadapter = BluetoothAdapter.getDefaultAdapter();

        //A100 API init
        if (mA100 == null) mA100 = RRUA100API.getInstance(new Handler());



        CommonPagerAdapter adapter = new CommonPagerAdapter(getSupportFragmentManager(), fragments);
        mViewPager.setOffscreenPageLimit(3);
        mViewPager.setAdapter(adapter);
        mAlphaIndicator.setViewPager(mViewPager);
      //  mViewPager.setCurrentItem(1);
    }

    boolean first_start = true;

    @Override
    public void onStart() {
        super.onStart();
        if (first_start) {
            if (mBTadapter == null) {
                //finish();
                return;
            }
            BT_enable_onStart = mBTadapter.isEnabled();
            if (BT_enable_onStart == false) {
                Intent BT_turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(BT_turnOn, 7001);
            } else {


                //bluetoothFragment.PairedListUpdate(mLast_addr);
            }
            first_start = false;
        }


    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mDevice != null) {
            boolean ret = mDevice.open();
            LogPlus.e("ret=" + ret);
        }
    }
//    @Override
//    protected void onPause() {
//        super.onPause();
//        // close UHF
//        mDevice.close();
//    }
    /**
     * 判断是否为仓管
     *
     * @return true：仓管；false：管理员
     */
    private boolean isStorekeeper() {
        return UserHelper.get().isStorekeeper();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Log.d("aaa", "返回了结果:" + requestCode);


        /**
         * 处理二维码扫描结果
         */
        if (requestCode == Constants.REQUEST_CODE.SCAN) {
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    Toast.makeText(this, "解析结果:" + result, Toast.LENGTH_LONG).show();
                    Intent intent = new Intent(MainActivity.this,BuCaoJiaoJieActivity.class);
                    intent.putExtra("orderno",result);
                    startActivity(intent);
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(MainActivity.this, "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        } else if(requestCode == BleHelper.REQUEST_ENABLE_BT){
            LogPlus.e("Ble","request_enable_bt");
            //自动连接
            if(!TextUtils.isEmpty(PreHelper.getBleDevice())) {
                BleHelper.getInstance().autoConnect(PreHelper.getBleDevice(), new BleHelper.BleConnectCall() {
                    @Override
                    public void connectCall(boolean isSuccess) {

                    }
                });
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //关闭蓝牙，关闭蓝牙读写线程
        BleHelper.getInstance().stopReadValue();
        BleHelper.getInstance().stopBle();
        if (mA100 != null) mA100.stop();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if(intent != null){
            String type = intent.getStringExtra("type"); //启动连接蓝牙页面
            if (!TextUtils.isEmpty(type) && "2".equals(type) && mViewPager != null){
                mViewPager.setCurrentItem(1);
            }
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //		Log.e("", "keycode == " + keyCode);
        if ( mAlphaIndicator.getCurrentItemView() == mTabB){
            mViewPager.setCurrentItem(0);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }




}
